
package nkr1pt.popkorn.download;

import java.io.File;
import java.util.logging.Logger;
import nkr1pt.popkorn.helper.FileUtils;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Kristof Vanhaeren
 */
public abstract class DownloadCandidateValidator {

    private static final Logger logger = Logger.getLogger(DownloadCandidateValidator.class.getName());

    public boolean validate(DownloadCandidate downloadCandidate) {
        if (doHostSpecificValidation(downloadCandidate) && doGenericValidation(downloadCandidate)) {
            return true;
        }

        downloadCandidate.setState(DownloadCandidateState.INVALID);
        return false;
    }

    protected abstract boolean doHostSpecificValidation(DownloadCandidate downloadCandidate);

    private boolean doGenericValidation(DownloadCandidate downloadCandidate) {
        boolean valid = true;
        valid = validateNotAlreadyCompleted(downloadCandidate);

        return valid;
    }

    private boolean validateNotAlreadyCompleted(DownloadCandidate downloadCandidate) {
        File dir = new File(downloadCandidate.getCompletedLocation() + File.separator + downloadCandidate.getName());
        if (FileUtils.isAccessable(dir)) {
            long size = 0L;
            for (File f : dir.listFiles()) {
                String name = FilenameUtils.removeExtension(FilenameUtils.getName(f.getName()));
                if (!name.equals(downloadCandidate.getName())) {
                    size += f.length();
                }
            }

            if (size >= downloadCandidate.getSize()) {
                logger.info(downloadCandidate.getName() + " ignored because it was already downloaded, see the complete downloads location.");
                return false;
            }
        }

        return true;
    }

}